﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using Aliphant.Interfaces;
using Aliphant.IoC;
using Aliphant.Script;
using Aliphant.Widget.Calendar.Views;

using Microsoft.ClearScript.V8;
using Microsoft.ClearScript;

using ScriptDemo.Views;
using System.IO;

namespace XWidgetDev
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Closed += MainWindow_Closed;
            //Test();
        }

        private void MainWindow_Closed(object? sender, EventArgs e)
        {
            page.Close();
        }

        public async void Test()
        {
            IScriptManager manager = new ScriptManager();

            //WidgetByScript widgetByScript = new WidgetByScript();
            //manager.Execute("F:\\Desktop\\中转\\Scripts\\b.js", widgetByScript, new string[] { "Aliphant.UI.Forms" });
            //widgetByScript.Close();

            Demo demo = new Demo();
            await manager.ExecuteAsync("F:\\Desktop\\中转\\Scripts\\b.js", demo, new string[] { "Aliphant.UI.Forms" });
            //demo.ExecuteScript();
            demo.ExecuteAction();
        }
    }

    public class Demo
    {
        public event Action? action;

        public void ExecuteScript()
        {
            string code = File.ReadAllText("F:\\Desktop\\中转\\Scripts\\b.js");


            IScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
            ScriptAgent agent = new ScriptAgent(engine);

            agent.InitHost();
            agent.RegisterObject(this);
            agent.RegisterEnv(new string[] { "Aliphant.UI.Forms" });
            agent.Evaluate(code);


            //string[] wpf = { "mscorlib", "System.Core", "PresentationCore", "PresentationFramework", "WindowsBase", "System.Runtime", "System.Threading.Tasks" };
            //engine.AddHostObject("wpf", new HostTypeCollection(wpf));     // 加载C#的程序集

            //AddDynamic(engine, this);

            
            //engine.Evaluate(code);
        }

        public void ExecuteAction()
        {
            action?.Invoke();
        }

        public static void AddDynamic(IScriptEngine engine, dynamic obj)
        {
            engine.AddHostObject("local", obj);
        }
    }
}